package com.rising.spring.advice;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

import java.util.Arrays;

@Component
public class LogAdvice2 {

    //抽取公共的切入点表达式
    //1、本类引用
    //2、其他的切面引用
    @Pointcut("execution(public void com.rising.spring.service.FruitService.eatFruit())")
    private void pointCut() {
    }

    ;

    @Before(value = "pointCut()")
    public void logStart(JoinPoint joinpoint) {
        System.out.println("Before>>>>" + joinpoint.getSignature().getName() + ">>>>" + Arrays.toString(joinpoint.getArgs()));
    }

    @After(value = "pointCut()")
    public void logEnd(JoinPoint joinpoint) {
        System.out.println("After>>>>>" + joinpoint.getSignature().getName() + ">>>>" + Arrays.toString(joinpoint.getArgs()));
    }

    @AfterReturning(value = "execution(public void com.rising.spring.service.FruitService.*(..))", returning = "object")
    public void logReturn(Object object) {
        System.out.println("AfterReturning>>>>" + object);
    }

    @AfterThrowing(value = "execution(public void com.rising.spring.service.FruitService.*(..))", throwing = "object")
    public void logException(Exception object) {
        System.out.println("AfterThrowing>>>>" + object);
    }

    @Around(value = "execution(public void com.rising.spring.service.FruitService.*(..))")
    public Object logException(ProceedingJoinPoint object) {
        Object rtValue = null;
        try {
            Object[] args = object.getArgs();//得到方法执行所需的参数

            System.out.println("Logger类中的aroundPringLog方法开始记录日志了。。。前置");

            rtValue = object.proceed(args);//明确调用业务层方法（切入点方法）

            System.out.println("Logger类中的aroundPringLog方法开始记录日志了。。。后置");

            return rtValue;
        } catch (Throwable t) {
            System.out.println("Logger类中的aroundPringLog方法开始记录日志了。。。异常");
            throw new RuntimeException(t);
        } finally {
            System.out.println("Logger类中的aroundPringLog方法开始记录日志了。。。最终");
        }
    }

}
